import {
  Controller,
  Get,
  Post,
  Body,
  Param,
  Put,
  Delete,
  Query,
  UseGuards,
  Request,
} from '@nestjs/common';
import { AddressService } from './address.service';
import { CreateAddressDto } from './dto/create-address.dto';
import { UpdateAddressDto } from './dto/update-address.dto';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard'; // 假设认证守卫路径与 book 模块一致

@Controller('api/address') // 接口路由
export class AddressController {
  constructor(private readonly addressService: AddressService) {}

  // 创建地址（需要认证）
  @UseGuards(JwtAuthGuard)
  @Post()
  async create(@Body() createAddressDto: CreateAddressDto, @Request() req) {
    // 从 JWT token 中获取用户 ID（假设 token 包含 sub 字段）
    const userId = req.user.sub;
    // 强制使用 token 中的 userId，防止前端篡改
    const address = await this.addressService.create({ ...createAddressDto, userId });
    return { code: 200, message: '地址创建成功', data: address };
  }

  // 获取用户所有地址（需要认证）
  @UseGuards(JwtAuthGuard)
  @Get()
  async findAll(@Request() req) {
    const userId = req.user.sub;
    const addresses = await this.addressService.findAll(userId);
    return { code: 200, message: '地址获取成功', data: addresses };
  }

  // 更新地址（需要认证）
  @UseGuards(JwtAuthGuard)
  @Put(':id')
  async update(
    @Param('id') id: string,
    @Body() updateAddressDto: UpdateAddressDto,
    @Request() req,
  ) {
    const userId = req.user.sub;
    const address = await this.addressService.update(+id, userId, updateAddressDto);
    return { code: 200, message: '地址更新成功', data: address };
  }

  // 删除地址（需要认证）
  @UseGuards(JwtAuthGuard)
  @Delete(':id')
  async remove(@Param('id') id: string, @Request() req) {
    const userId = req.user.sub;
    await this.addressService.remove(+id, userId);
    return { code: 200, message: '地址删除成功' };
  }

  // 获取单个地址详情（需要认证）
  @UseGuards(JwtAuthGuard)
  @Get(':id')
  async findOne(@Param('id') id: string) {
    const address = await this.addressService.findOne(+id);
    return { code: 200, message: '地址获取成功', data: address };
  }
}